package mysqldb

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"time"
)

type MysqlDb struct {
	db *xorm.Engine
}

func NewMysqlData(username string, password string, host string, port int, database string) (*MysqlDb, error) {
	mysqlDb := &MysqlDb{}
	var err error
	connString := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		username, password, host, port, database)

	mysqlDb.db, err = xorm.NewEngine("mysql", connString)
	mysqlDb.db.SetMaxOpenConns(2000)
	mysqlDb.db.SetMaxIdleConns(1000)
	mysqlDb.db.SetConnMaxLifetime(time.Hour)

	err = mysqlDb.db.Ping()
	if err != nil {
		return nil, err
	}

	return mysqlDb, err
}

func (this *MysqlDb) Insert(value interface{}) (int64, error) {
	return this.db.Insert(value)
}

func (this *MysqlDb) Delete(key interface{}, value interface{}) (int64, error) {
	return this.db.ID(key).Delete(value)
}

func (this *MysqlDb) Update(key interface{}, value interface{}) (int64, error) {
	return this.db.Id(key).Update(value)
}

func (this *MysqlDb) Exec(sql string) (sql.Result, error) {
	return this.db.Exec(sql)
}

func (this *MysqlDb) Get(key interface{}, value interface{}) (bool, error) {
	return this.db.ID(key).Get(value)
}

func (this *MysqlDb) Query(sql string) (resultsSlice []map[string][]byte, err error) {
	return this.db.Query(sql)
}

func (this *MysqlDb) Sync2(beans ...interface{}) error {
	return this.db.Sync2(beans...)
}
